package com.andova.pipeline

import android.os.Handler
import android.os.HandlerThread
import android.os.Message
import com.andova.egl.OnTextureBridger
import com.andova.glcamera.pool.HdrThreadFactory.Companion.get

class PipelineHandler(private val bridger: OnTextureBridger) : Handler.Callback {
    @Volatile
    private var mlock = false

    @Volatile
    private var mBuffer: ByteArray? = null
    private var mHandler: Handler? = null
    private var mThread: HandlerThread? = null
    fun isBusy() = mlock
    fun getBuffer() = mBuffer
    private fun stop(key: String) = get().destroy(key)
    fun start(key: String) {
        mThread = get().borrow(key).apply {
            if (mHandler != null) return@apply
            mHandler = Handler(looper, this@PipelineHandler)
        }
    }

    fun sendMessage(msg: Message) = mHandler?.sendMessage(msg)
    override fun handleMessage(message: Message): Boolean {
        if (mlock) return false
        mlock = true
        mBuffer = (message.obj as? ByteArray)?.apply {
            bridger.onPreviewFrame(this.clone())
        }
        mlock = false
        return true
    }
}